package top.rish.converter.handler;

import top.rish.converter.annotation.DesensitizedConverter;
import top.rish.converter.base.DesensitizedAction;
import top.rish.converter.base.DictEntity;
import top.rish.converter.info.FieldWrap;
import top.rish.converter.info.MetaMap;
import top.rish.converter.utils.ObjKit;
import top.rish.converter.utils.RefKit;

import java.util.HashMap;
import java.util.Map;

public class DesensitizedConverterHandler implements ConvertHandler<DesensitizedConverter> {

    private static final Map<Class<?> ,DesensitizedAction> CLASS_AND_DESENSITIZED_ACTION
            = new HashMap<>();

    @Override
    public void convert(MetaMap mateMap,
                        DictEntity entity,
                        Object value,
                        FieldWrap fieldWrap,
                        DesensitizedConverter convert) {
        if(ObjKit.isEmpty(value)){
            return;
        }
        Class<? extends DesensitizedAction> dc = convert.value();
        Object aClass = RefKit.getGenericClass(dc, 0);
        if(fieldWrap.getType() != aClass){
            return;
        }
        try {
            DesensitizedAction action = CLASS_AND_DESENSITIZED_ACTION.get(dc);
            if(action==null){
                action = dc.newInstance();
                CLASS_AND_DESENSITIZED_ACTION.put(dc,action);
            }
            mateMap.put(fieldWrap.getName(),action.desensitized(value));
        } catch (Exception e) {

        }

    }
}
